package com.wt.springsamples.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8000));
        //在没有客户端连接时serverSocketChannel.accept()不会阻塞
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

        while (true){//循环等待客户端连接
            if(selector.select()==0) continue;
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isAcceptable()){
                    //serverSocketChannel.configureBlocking(false);//在没有客户端连接时accept()不会阻塞
                    SocketChannel accept = serverSocketChannel.accept();
                    System.out.println("客户端"+accept.getLocalAddress()+"连接成功！！");
                    accept.configureBlocking(false);
                    accept.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(512));
                }
                if(selectionKey.isReadable()){
                    SocketChannel socketChannel  = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer)selectionKey.attachment();
                    socketChannel.read(byteBuffer);
                    System.out.println("from 客户端："+new String(byteBuffer.array()));
                }
                iterator.remove();
            }
        }
    }
}
